package com.ujs.service.impl;

import com.ujs.dao.AuthorityDao;
import com.ujs.dao.RoleDao;
import com.ujs.pojo.Authority;
import com.ujs.pojo.Role;
import com.ujs.pojo.UserInfo;
import com.ujs.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AuthorityDao authorityDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Role findById(String id) {
        return roleDao.getOne(id);
    }

    @Override
    public void save(Role role) {
        roleDao.save(role);
    }

    @Override
    public void deleteById(String id) {
        roleDao.deleteById(id);
    }

    @Override
    public List<Authority> findOtherAuthority(String roleId) {
        Role role = roleDao.getOne(roleId);
        Set<Authority> authorities = role.getAuthorities();
        List<Authority> all = authorityDao.findAll();
        for (Authority authority : authorities) {
            if (all.contains(authority)) {
                all.remove(authority);
            }
        }
        return all;
    }

    @Override
    public void addAuthorityToRole(String roleId, String[] authorityIds) {
        Role role = roleDao.getOne(roleId);
        for (String authorityId : authorityIds) {
            Authority authority = authorityDao.getOne(authorityId);
            role.getAuthorities().add(authority);
        }
        roleDao.save(role);

    }
}